﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Mobile.Models;
using SDT.Model;
using System.Linq.Dynamic;
using SDT.Mobile.Properties;
using SDT.Lib.Paging;
using SDT.Lib.Common;
using SDT.Lib.Helpers;
using System.Data.Linq;
namespace SDT.Mobile.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/
        SDTDataContext db = new SDTDataContext();
       
            
        public ActionResult Details(int id)     
        {
            ProductDetailsModels p = new ProductDetailsModels();
            p.Product = db.Products.Where(e =>e.ID == id).SingleOrDefault();
            p.Product.nViews += 1;
            db.SubmitChanges();
            string subPath = string.Format("{0}\\{1}\\{2}\\", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);
            string subUrl = string.Format("{0}/{1}/{2}/", p.Product.AddDate.Value.Year, p.Product.AddDate.Value.Month, p.Product.AddDate.Value.Day);

            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl + subUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath + subPath;
            p.Directions = Utils.StringToDictionaryIntString(Settings.Default.ProductDirection, ",");

            p.ProductSearch = new ProductSearchModels();
            p.ProductSearch.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            if (p.Product.CityID > 0)
            {
                p.ProductSearch.Districts = ProductManager.GetDistrict(p.Product.TypeID, p.Product.CatID, p.Product.CityID);
                p.ProductSearch.City = p.Product.City;
            }
            else
            {
                p.ProductSearch.Districts = new List<District>();
            }
            p.ProductSearch.Categories = ProductManager.GetObjChildByType(p.Product.TypeID);
            p.ProductSearch.Cities = ProductManager.GetCity(p.Product.TypeID, p.Product.CatID);
            p.ProductSearch.ConvertPrices = ProductManager.GetConvertPrice(p.Product.TypeID);
            p.ProductSearch.ConvertAreas = ProductManager.GetConvertArea(p.Product.TypeID);
            p.ProductSearch.ProductTypes = db.ProductTypes.ToList();


            p.ProductSearch.ProductType = p.Product.ProductType;
            p.ProductSearch.Category = p.Product.ProductCategory;
            p.ProductSearch.District = p.Product.District;
            p.ProductSearch.ConvertPrice = p.Product.ConvertPrice1;
            p.ProductSearch.ConvertArea = p.Product.ConvertArea1;

            p.ProductSearch.AreaID = p.Product.ConvertArea;
            p.ProductSearch.CategoryID = p.Product.CatID;
            p.ProductSearch.CityID = p.Product.CityID;
            p.ProductSearch.DistrictID = p.Product.DistrictID;
            p.ProductSearch.PriceID = p.Product.ConvertPrice;
            p.ProductSearch.TimeID = 0;
            p.ProductSearch.TypeID = p.Product.TypeID;
            p.ProductSearch.ProjectID = 0;
            p.ProductSearch.PathTitle = p.Product.Title;
            p.Keyword = string.Empty;

            return View(p);
        }
       
        
        public ActionResult Index(int? id, int? catid, int? cityid, int? distrid, int? areaid, int? priceid, int? projectid, int? timeid, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("product.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("product.order", "order", "AddDate").ToString();
            string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
            int getbyTimeID = Utils.ParseInt(UserState.getUserStateFromRequest("product.TimeID", "ddlTimeCenter", 0));
            string keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;
            var postYN = Request.HttpMethod == "POST" ? true : false;
            switch (order)
            {
                case "AddDate":
                    orderDir = "desc";
                    break;
                case "nViews":
                    orderDir = "desc";
                    break;
                case "TotalCost":
                    orderDir = "asc";
                    break;
            }            
            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            ProductSearchModels p = new ProductSearchModels();
            p.AreaID = areaid;
            p.CategoryID = catid;
            p.CityID = cityid;
            p.DistrictID = distrid;
            p.PriceID = priceid;
            p.TimeID = postYN ? getbyTimeID : (timeid.HasValue ? timeid.Value : 0);
            p.TypeID = id;
            p.ProjectID = projectid;
            p.Keyword = postYN ? keyword : (Request["key"] != null ? Request["key"] : string.Empty);
            p.Products = ProductManager.GetList(p.TypeID, p.CategoryID, p.CityID, p.DistrictID,
                p.AreaID, p.PriceID, p.ProjectID, p.TimeID, p.Keyword, 0, 1,
                order, orderDir, pageIndex, Utils.ParseInt(Settings.Default.ProductPageSize), null); // Added parameter Guide.Emty (Vietlv  - 12/09/2011)
            
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;

            if (p.CityID > 0)
            {
                p.Districts = ProductManager.GetDistrict(p.TypeID.Value, p.CategoryID.Value, p.CityID.Value);
                p.City = db.Cities.Where(e => e.ID == p.CityID).SingleOrDefault();
            }

            else
            {
                p.Districts = new List<District>();

            }
            p.Times = Utils.StringToDictionaryIntString(Settings.Default.SearchByTime, ";");
            p.Categories = id > 0 ? ProductManager.GetObjChildByType(id.Value) : null;
            p.Cities = ProductManager.GetCity(p.TypeID.Value, p.CategoryID.HasValue ? p.CategoryID.Value : 0);
            p.ConvertPrices = ProductManager.GetConvertPrice(p.TypeID.Value);
            p.ConvertAreas = ProductManager.GetConvertArea(p.TypeID.Value);
            p.ProductTypes = db.ProductTypes.ToList();


            p.ProductType = db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault();
            p.Category = db.ProductCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault();
            p.District = db.Districts.Where(e => e.ID == p.DistrictID).SingleOrDefault();
            p.ConvertPrice = db.ConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault();
            p.ConvertArea = db.ConvertAreas.Where(e => e.ID == p.AreaID).SingleOrDefault();
            p.Currencies = Utils.StringToDictionaryIntString(Settings.Default.ListCurrency, ",");


            return View(p);
        }
        [Authorize()]
        public ActionResult AddProduct(int? id)
        {
            var p = new ProductListModels();
            //int cityid = Request["CityID"] !=null? Utils.ParseInt(Request["CityID"]):0;
            p.ProductTypes = db.ProductTypes.ToList();
            p.ProductCategorys = db.ProductCategories.ToList();
            p.Cities = db.Cities.ToList();
            p.Districts = db.Districts.Where(e =>e.CityID.Equals(id)).ToList();
            Product pro = new Product();
            pro.TypeID = Request["ddProductType"] !=null? Utils.ParseInt(Request["ddProductType"]):0;
            pro.CatID = Request["ddProducCate"] != null ? Utils.ParseInt(Request["ddProducCate"]) : 0;
            pro.CityID = Request["ddlCity"] != null ? Utils.ParseInt(Request["ddlCity"]) : 0;
            pro.DistrictID = Request["ddlDistrict"] != null ? Utils.ParseInt(Request["ddlDistrict"]) : 0;
            pro.Title = Request["title"];
            pro.Summary = Request["content"];
            pro.ContactMobile = Request["mobile"];
            pro.AddDate = DateTime.Now;
            pro.PubYN = false;
            pro.HotYN = false;
            pro.VipYN = false;
           // pro.AddBy = UserManager.GetUserId();
            if (pro.TypeID > 0 && pro.CatID > 0 && pro.CityID > 0 && pro.DistrictID > 0 && pro.Title != "" && pro.Title != null && pro.Summary != "" && pro.Summary != null)
            {
                db.Products.InsertOnSubmit(pro);
                db.SubmitChanges();
                return View("success");
            }
            else
            {
                return View(p);
            }
        }
        [ChildActionOnly]
        public ActionResult Search(int typeid)
        {
            ProductSearchModels p = new ProductSearchModels();
            p.Categories = db.ProductCategories.Where(e => e.TypeID == typeid).OrderBy(string.Format("{0} {1}", "Priority", "asc")).ToList();
            p.ProductTypes = db.ProductTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();

            p.Cities = db.Cities.OrderBy(string.Format("{0} {1}", "Name", "asc")).ToList();
            p.ConvertAreas = db.ConvertAreas.Where(e => e.TypeID == typeid).ToList();
            p.ConvertPrices = db.ConvertPrices.Where(e => e.TypeID == typeid).ToList();

            return View(p);
        }
        [ChildActionOnly]
        public ActionResult TopSearch(int typeID, string keyword)
        {
            ProductTopSearchModels p = new ProductTopSearchModels();            
            p.ProductTypes = db.ProductTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();
            p.Keyword = keyword;
            p.TypeID = typeID;
            return View(p);
        }
        public ActionResult SearchAdv(int id)
        {
            ProductSearchModels p = new ProductSearchModels();
            p.Categories = db.ProductCategories.Where(e => e.TypeID == id).OrderBy(string.Format("{0} {1}", "Priority", "asc")).ToList();
            p.ProductTypes = db.ProductTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();

            p.Cities = db.Cities.OrderBy(string.Format("{0} {1}", "Name", "asc")).ToList();
            p.ConvertAreas = db.ConvertAreas.Where(e => e.TypeID == id).ToList();
            p.ConvertPrices = db.ConvertPrices.Where(e => e.TypeID == id).ToList();

            return View(p);
        }
        [HttpPost()]
        public ActionResult Search(ProductSearchModels p)
        {

            p.AreaID = Utils.ParseInt(Request["ddlArea"], 0); ;
            p.CategoryID = Utils.ParseInt(Request["ddlCategory"], 0);
            p.CityID = Utils.ParseInt(Request["ddlCity"], 0);
            p.DistrictID = Utils.ParseInt(Request["ddlDistrict"], 0);
            p.PriceID = Utils.ParseInt(Request["ddlPrice"], 0);
            p.TimeID = Utils.ParseInt(Request["ddlTime"], 0);
            p.TypeID = Utils.ParseInt(Request["ddlType"], 0);
            p.ProjectID = 0;

            var firstName = p.TypeID > 0 ? db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault().Name : "Bất động sản bán";
            firstName = p.CategoryID.HasValue && p.CategoryID > 0 ? db.ProductCategories.Where(e => e.ID == p.CategoryID).SingleOrDefault().Name : firstName;
            var clientName = p.CityID > 0 ? firstName + " tại " + db.Cities.Where(e => e.ID == p.CityID).SingleOrDefault().Name : firstName;
            clientName = p.DistrictID > 0 ? firstName + " tại " + db.Districts.Where(e => e.ID == p.DistrictID).SingleOrDefault().Name + " " + db.Cities.Where(e => e.ID == p.CityID).SingleOrDefault().Name : clientName;
            clientName = p.AreaID > 0 ? clientName + " diện tích: " + db.ConvertAreas.Where(e => e.ID == p.AreaID).SingleOrDefault().Name : clientName;
            clientName = p.PriceID > 0 ? clientName + " giá: " + db.ConvertPrices.Where(e => e.ID == p.PriceID).SingleOrDefault().Name : clientName;

            p.Keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;

            var path = "/" + TextHelper.ToUrlFriendly(clientName) + string.Format("/p/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}",
                   p.TypeID.HasValue ? p.TypeID.Value : 0,
                   p.CategoryID.HasValue ? p.CategoryID.Value : 0,
                   p.CityID.HasValue ? p.CityID.Value : 0,
                   p.DistrictID.HasValue ? p.DistrictID.Value : 0,
                   p.AreaID.HasValue ? p.AreaID.Value : 0,
                   p.PriceID.HasValue ? p.PriceID.Value : 0,
                   p.ProjectID.HasValue ? p.ProjectID.Value : 0,
                   p.TimeID.HasValue ? p.TimeID.Value : 0);
            path = TextHelper.ToUrlShort(path);
            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return Redirect(path);
        }
        [HttpPost()]
        public ActionResult TopSearch(ProductTopSearchModels p)
        {
            p.TypeID = Utils.ParseInt(Request["ddlProductType"], 0);
           
            var firstName = p.TypeID > 0 ? db.ProductTypes.Where(e => e.ID == p.TypeID).SingleOrDefault().Name : "Tìm kiếm bất động sản";
            var clientName = firstName;
            p.Keyword = Request["txtProductKeyword"] != null ? Request["txtProductKeyword"] : string.Empty;

            var path = "/" + TextHelper.ToUrlFriendly(clientName) + string.Format("/p/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}",
                   p.TypeID.HasValue ? p.TypeID.Value : 0,0,0,0,0,0,0,0);
            path = TextHelper.ToUrlShort(path);
            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return Redirect(path);
        }
        public ActionResult success()
        {
            var p = new ProductListModels();
            p.ProductTypes = db.ProductTypes.ToList();
            p.ArticleCategorys = db.ArticleCategories.ToList();
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult Gets(int typeid, int? catid, int number, string order, string orderDir, string viewName, string title)
        {
            var p = new ProductModels();
            var db = new SDTDataContext();
            var l = db.Products.Where(e => typeid > 0 ? e.TypeID == typeid : true)
                .Where(e => catid > 0 ? e.CatID == catid.Value : true)
                .Where(e => e.PubYN == true)
                .OrderBy(string.Format("{0} {1}", order, orderDir)).Take(number).ToList();
            p.Products = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ProductRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ProductRootPath;
            p.Currencies = Utils.StringToDictionaryIntString(Settings.Default.ListCurrency, ",");
            ViewData["Title"] = title;
            return PartialView(viewName,p);
        }
    }
}
